// app端访问

var express = require("express");
var router = express.Router();
var my_fs = require("../tools/fs");
// import my_fs from "../tools/fs"
var moment = require("moment");
var mysql = require("mysql");
var http = require("http");
var qs = require("querystring");

const bodyParser = require("body-parser");

/* GET home page. */
router.get("/", get_index);

/* GET access log. */
router.get("/access", access);
router.post("/getaccess", get_access);
router.post("/getupload", get_upload);

// chat
router.get("/chat", function(req, res, next) {
  console.log('chart get html');
  res.render("chat")
})
router.get("/chats", function(req, res, next) {
  console.log('chart get html');
  res.render("chats")
})

// 校验版本号
// router.post("/orderled-version", get_version);

// methods ------------------------------------------------------------------------------------

// var connection = null
async function get_index(req, res, next) {
  console.log("--------- in  ---------");
  console.log("ip:" + req.ip);
  console.log("xhr:" + req.xhr);
  console.log("protocol:" + req.protocol);

  // my_fs.stat("./test.txt").then(ret=>{
  //   console.log(ret);
  // })
  let time = moment().format("YYYY-MM-DD HH:mm:ss");

  // 1 txt ========================
  // let text = "get|" + req.protocol + "|" + req.ip + "|" + time + "\n";

  // let ret = await my_fs.append("./log/access.log", text);

  // ==================== ip归属地 start ==========================
  let ip_data = await get_ip_location(req.ip)
  let location = ip_data.location
  console.log('location ->');
  console.log(location);
  // ==================== ip归属地 end   ==========================

  // 2 json ========================
  let json = await my_fs.read("./log/access.json");
  // return console.log('json: ---' + json);
  if (json == null || json == "" || json == undefined) json = false
  else json = JSON.parse(json)
  
  // console.log("read");
  // console.log(json);
  if (json == false || json.access == []) {
    console.log("read err------------------------------------------------");
    json = {
      access: [],
      ip_pool: [],
    };
    json.access.unshift({
      protocol: req.protocol,
      headers: req.headers,
      host: req.host,
      xhr: req.xhr,
      time,
      ip: req.ip,
      path: req.path,
      location
    });
    json.ip_pool.push({
      ip: req.ip,
      num: 1,
    });
  } else {
    json.access.unshift({
      protocol: req.protocol,
      headers: req.headers,
      host: req.host,
      xhr: req.xhr,
      time,
      ip: req.ip,
      path: req.path,
      location
    });
    // +
    let num_flag = true;
    for (let i = 0; i < json.ip_pool.length; i++) {
      const ele = json.ip_pool[i];
      if (req.ip == ele.ip) {
        console.log("已经访问过");
        ele.num++;
        console.log(ele.num + "次访问");
        num_flag = false;
      }
    }
    //
    if (num_flag) {
      console.log("没有访问过");
      json.ip_pool.push({
        ip: req.ip,
        num: 1,
      });
    }
  }

  // console.log(json);
  let ret_json = await my_fs.write("./log/access.json", JSON.stringify(json));

  if (ret_json) {
    // console.log(ret_json);
    res.render("index", { ip: req.ip });
    console.log("--------- end ---------");
  } else {
    console.log(ret_json);
    res.render("error");
    console.log("--------- end ---------");
  }
}

// access
async function access(req, res, next) {
  res.render("access.html");
}


// 获取访问数据
async function get_access(req, res, next) {
  let json = await my_fs.read("./log/access.json");
  json = JSON.parse(json);
  console.log("访问记录");
   
  res.json(json);
}

// 获取上传记录
async function get_upload(req, res, next) {
  let json = await my_fs.read("./log/upload.json");
  json = JSON.parse(json);
  // json.req = req
  res.json(json);
}

// fn -----------------------------------------------------

// 根据ip获取相关信息(异步封装)
function get_ip_location(ip) {
  return new Promise((cb, rej) => {
    let post_data = qs.stringify({ ip });
    var options = {
      hostname: "localhost",
      port: 9604,
      path: "/iptool",
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    };

    var req = http.request(options, function (res) {
      console.log("STATUS: " + res.statusCode);
      console.log("HEADERS: " + JSON.stringify(res.headers));
      res.setEncoding("utf8");
      res.on("data", function (chunk) {
        console.log("BODY: " + chunk);
        let json = JSON.parse(chunk)
        cb(json)
      });
    });

    req.on("error", function (e) {
      console.log("problem with request: " + e.message);
      cb(false)
    });

    // 将数据写入请求体
    req.write(post_data); //注意这个地方

    req.end();
  });
}

module.exports = router;
